<template>
  <div
    class="Index"
    :style="{ transform: 'translateY(' + scroll + 'px)', 'z-index': zindex }"
  >
    <!-- <stepmain/> -->
    <van-nav-bar @click-right="onAddDevice">
      <!-- <van-popover :v-model:show="showPopover" :actions="actions"> -->
      <template #left>
        <p style="color: black; font-weight: 500; font-size: 16px">首页</p>
      </template>
      <template #right>
        <van-icon name="add" size="22" />
      </template>
      <!-- </van-popover> -->
    </van-nav-bar>

    <van-action-sheet
      style="text-align: center; background-color: #f2f3f5"
      v-model="show"
      title="请输入设备码"
      @click-overlay="zindex = 0"
    >
      <van-password-input
        style="margin-bottom: 270px; margin-top: 20px"
        :value="values"
        :mask="false"
        :focused="keyshow"
        @focus="keyshow = true"
      />
      <!-- <van-icon
        name="scan"
        size="36"
        style="position: absolute; bottom: 240px; right: calc(50vw - 18px)"
        @click="onScanQRCode"
      /> -->
      <van-loading
        v-if="loadshow"
        style="text-align: center; bottom: 150px; position: relative"
        color="#1989fa"
        vertical
        >添加中...</van-loading
      >
      <van-number-keyboard
        v-model="values"
        theme="custom"
        delete-button-text="删除"
        close-button-text="扫码"
        @close="onScanQRCode"
        @blur="show = false;zindex = 0;"
        :show="keyshow"
      />
    </van-action-sheet>
    <!-- <van-notice-bar mode="closeable" scrollable
      >由于服务器到期，需要将硬件代码中的121.5.58.100更换为103.73.162.251</van-notice-bar
    > -->
    <van-tabs v-model="activeName" animated>
      <van-tab id="devicetab" title="我的设备" name="device">
        <van-pull-refresh
          :disabled="refresh"
          pull-distance="1000px"
          v-model="pload"
          @refresh="updateDevice"
          style="min-height: calc(100vh - 160px); padding-bottom: 10px"
        >
          <div style="padding-top: 10px">
            <van-loading
              v-if="load"
              style="text-align: center; width: 100%; position: relative"
              size="24px"
              :key="panel"
              >加载中...</van-loading
            >
            <transition-group>
              <div class="empty" v-if="emptyView" :key="panel">
                <van-empty description="暂无设备，可点击右上角添加" />
              </div>
              <van-swipe-cell v-else v-for="item in panel" :key="item.id">
                <component
                  :is="item.name"
                  :name="item.devicename"
                  :id="item.id"
                  :pub="item.mqttPub"
                  :sub="item.mqttSub"
                  :deviceInfo="item"
                />
                <template #right>
                  <van-button
                    @click="onDeleteDevice(item.id)"
                    square
                    text="删除"
                    type="danger"
                    class="delete-button"
                    style="
                      height: calc(100% - 20px);
                      margin-top: 10px;
                      margin-right: 20px;
                      border-radius: 20px;
                      box-shadow: 0px 0px 12px 0 rgb(0 0 0 / 8%);
                    "
                  />
                </template>
              </van-swipe-cell>
            </transition-group>
          </div>
        </van-pull-refresh>
      </van-tab>
      <!-- <van-tab title="房间" name="room">
        <div
          style="overflow: auto; height: calc(100% - 160px); padding-top: 10px"
        >
          <RoomTab :name="null" />
        </div>
      </van-tab>

      <van-tab title="分组" name="group">
        <div
          style="overflow: auto; height: calc(100% - 160px); padding-top: 10px"
        >
          <GroupTab :name="null" /></div
      ></van-tab> -->
    </van-tabs>

    <router-view></router-view>
  </div>
</template>

<script>
import { queryUserByuserId } from "@/api/api";
import { PullRefresh } from "vant";
import mqtt from "mqtt";
import InterFacePage from "@c/InterFacePage/Banner";
import CustomPage from "@c/CustomPage/Banner";
import RoomTab from "@v/Home/RoomTab.vue";
import GroupTab from "@v/Home/GroupTab.vue";
import Relay from "@c/CustomPages/Relay/Relay.vue";
import MQ from "@c/CustomPages/MQ/MQ.vue";
import Light from "@c/CustomPages/Light/Light.vue";
import Fish from "@c/CustomPages/Fish/Fish.vue";
import SmartLight from "@c/CustomPages/SmartLight/SmartLight.vue";
import LMGETDY from "@c/CustomPages/LMGETDY/Banner";
import Step from "@c/CustomPages/Step/Step.vue";
import Skin from "@c/CustomPages/Skin/Skin";
import LRBL from "@c/CustomPages/LRBL/LRBL.vue";
import Farm from "@c/Farm/Banner";
import Farm_2 from "@c/Farm_2/Banner";
import Lab_1 from "@c/Lab_1/Banner";
import LYCWDW from "@c/LYCWDW/Banner";
import Dorm from "@c/Dorm/Banner";
import SmartKit from "@c/SmartKit/Banner";
import Position from "@c/Position/Banner";
import Position2 from "@c/Position2/Banner";
import Express1 from "@c/Express1/Banner";
import Cat_Home from "@c/Cat_Home/Banner";
import RemotePower from "@c/RemotePower/Banner";
import RemoteAir from "@c/RemoteAir/Banner";
import cDevice1 from "@c/cDevice1/Banner";
import FailDetect_1 from "@c/FailDetect_1/Banner";
import MircoStep_1 from "@c/MircoStep_1/Banner";
import LXNCDWDW from "@c/CustomPages/LXNCDWDW/Banner";
import { Toast } from "vant";
var client;
const options = {
  connectTimeout: 40000,
  clean: true,
};
client = mqtt.connect("ws://121.5.58.100:8083/mqtt", options);
export default {
  name: "home",

  components: {
    CustomPage,
    InterFacePage,
    RoomTab,
    GroupTab,
    Relay,
    MQ,
    Light,
    Fish,
    SmartLight,
    Step,
    Skin,
    LRBL,
    Farm,
    Farm_2,
    Lab_1,
    LYCWDW,
    LMGETDY,
    LXNCDWDW,
    Dorm,
    SmartKit,
    Position,
    Position2,
    Express1,
    Cat_Home,
    cDevice1,
    RemotePower,
    RemoteAir,
    FailDetect_1,
    MircoStep_1
  },
  activated: function () {
    console.log(this.panel);
    // 在 keepAlive 被激活的时候，调用指定加载页面组件的方法
    //var res = localStorage.getItem("Background");
    //console.log(res);
    //this.resetSetItem("Background", res);
    // handleScroll();
    this.scroll = 0;
    this.refresh = false;
    console.log("Home-keepok");
    console.log(this.$route.params.value);
    this.getQRCodeBack(this.$route.params.value);
    this.$route.params.value = "";
    // console.log(this.Background);
  },
  data() {
    return {
      refresh: false,
      zindex: 0,
      scroll: 0,
      activeName: "device",
      showPopover: true,
      id: localStorage.getItem("setUserID"),
      load: true,
      pload: false,
      show: false,
      keyshow: true,
      values: "",
      loadshow: false,
      panel: [],
      Background: "",
      emptyView: false,
    };
  },
  watch: {
    values(value) {
      if (value > 99999) {
        navigator.vibrate(100);
        this.keyshow = false;
        this.loadshow = true;
        this.$http
          .get("http://121.5.58.100:8000/updateDevice", {
            params: {
              userid: localStorage.getItem("setUserID"),
              id: value,
            },
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
          })
          .then((result) => {
            if (result.data.description === "UpdateSuccess") {
              this.zindex = 0;
              Toast.success("添加成功");
              this.loadshow = false;
              this.show = false;
              this.updateDevice();
              this.values = "";
            } else if (result.data.description === "NotFind") {
              Toast.fail("设备不存在");
              this.loadshow = false;
              this.show = true;
              this.keyshow = true;
              this.values = "";
            } else if (result.data.description === "ReUpdate") {
              Toast.fail("设备已存在");
              this.loadshow = false;
              this.show = true;
              this.keyshow = true;
              this.values = "";
            } else if (result.data.description === "NotAllow") {
              Toast.fail("该设备不允许被添加");
              this.loadshow = false;
              this.show = true;
              this.keyshow = true;
              this.values = "";
            }
            //this.panel = result.data;
          });
      }
    },
    deep: true,
  },
  mounted: function () {
    this.load = true;
    document.addEventListener("scroll", this.handleScroll, true);
    console.log("homecreaye");
    this.updateDevice();
    // handleScroll();
  },
  methods: {
    handleScroll() {
      var Top = document.getElementById("devicetab").scrollTop;
      var Bottom =
        document.getElementById("devicetab").scrollHeight -
        document.getElementById("devicetab").scrollTop;

      if (Top <= 46) {
        this.scroll = Top * -1;
      } else {
        this.scroll = -46;
      }
      if (document.getElementById("devicetab").clientHeight === Bottom) {
        console.log(
          document.getElementById("devicetab").clientHeight === Bottom
        );
        this.scroll = -46;
      }
      console.log(Top);
      if (Top) {
        this.refresh = true;
      } else {
        this.refresh = false;
      }
    },
    getQRCodeBack(payload) {
      console.log(payload);
      this.values = payload;
    },
    onScanQRCode() {
      console.log("ok");
      this.$router.push({
        name: "scanqrcode",
        params: {
          routerType: "push",
        },
      });
    },
    exit() {
      localStorage.setItem("islogin", 0);
      this.$router.go(0);
      console.log("ok");
    },
    onDeleteDevice(aid) {
      // console.log(aid)
      this.$http
        .get("http://121.5.58.100:8000/deleteDeviceUserInfo", {
          params: {
            userid: localStorage.getItem("setUserID"),
            id: aid,
          },
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((result) => {
          if (result.data.description === "DeleteSuccess") {
            Toast.success("删除成功");
            this.updateDevice();
          } else if (result.data.description === "NotFind") {
            Toast.fail("删除失败");
          }
          //this.panel = result.data;
        });
    },
    onAddDevice() {
      // this.$router.push({
      //   name: "test",
      // });
      (this.zindex = 10), (this.keyshow = true);
      this.show = true;
    },
    updateDevice2() {
      console.log("更新组件");
    },
    updateDevice() {
      console.log("更新组件与MQTT");
      this.$mqtt.end();
      this.$mqtt.launch("ws://121.5.58.100:8083/mqtt");
      this.panel = [];
      this.pload = true;
      var params = {
        userid: localStorage.getItem("setUserID"),
      };

      queryUserByuserId(params).then((result) => {
        this.load = false;
        this.pload = false;
        console.log(result.length);
        if (result.length === 0) {
          this.emptyView = true;
        } else {
          this.emptyView = false;
        }
        this.$store.commit("saveDeviceNumber", result.length);
        this.panel = [];
        for (let i = 0; i < result.length; i++) {
          if (result[i].type === "customize") {
            this.panel.push(result[i]);
          } else if (result[i].type === "default") {
            this.panel.push(result[i]);
            this.panel[i].devicename = result[i].name;
            this.panel[i].name = "InterFacePage";
          }
          this.$mqtt.subscribe(result[i].mqttPub);
        }
      });
    },
  },
};
</script>

<style scoped>
.v-enter,
.v-leave-to {
  opacity: 0;
  transform: translateY(200px);
}

.v-enter-active,
.v-leave-to {
  transition: all 0.6s ease;
}

/* v-move 和 v-leave-to 配合使用，能够实现列表后续的元素，逐渐飘上来的效果 */
.v-move {
  transition: all 0.6s ease;
}

.v-leave-to {
  position: absolute;
}
.Index {
  transition: 0.1s;
  height: 100%;
  overflow: hidden;
  background-color: transparent;
}
.text {
  color: white;
  text-align: left;
  margin-left: 5vw;
  margin-bottom: 10vw;
}
#devicetab {
  overflow: auto;
  height: calc(100vh - 94px);
}
.empty {
  z-index: 1;
  height: auto;
  border-radius: 20px;
  margin: 20px 20px;
  box-shadow: 0px 0px 12px 0 rgb(0 0 0 / 8%);
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(20px) saturate(180%);
}
.van-tabs__line {
  position: absolute;
  bottom: 15px;
  left: 0;
  z-index: 1;
  width: 40px;
  height: 3px;
  background-color: #1989fa;
  border-radius: 3px;
}
</style>
